package dk.flashnotes.fff.helpers {
	import dk.flashnotes.fff.FFFBase;	
	import dk.flashnotes.fff.helpers.Helper;
	
	import org.osflash.thunderbolt.Logger;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.net.SharedObject;	

	/**
	 * @author jk
	 */
	public class HelpersControl {

		private var _doHelperHolder : Sprite;
		private var _a_doHelpers : Array;

		private var _oSOVisibleState : SharedObject; 
		private var _sSO_VISIBLE_STATE_KEY : String="soHelpersVisibleState";
		private var _sSTATE_KEY : String="state";
		private var _sON : String = "on";
		private var _sOFF : String = "off";
		
		public static var uintTOGGLE_HELPER_CHAR_CODE_WIN : uint=116;
		public static var uintTOGGLE_HELPER_CHAR_CODE_MAC : uint=20;

		public function HelpersControl(doHelperHolder : Sprite) {
			
			_doHelperHolder = doHelperHolder;
			_doHelperHolder.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true);
			
			// check so
			_oSOVisibleState = SharedObject.getLocal(_sSO_VISIBLE_STATE_KEY);
			
			if (!_oSOVisibleState.data[_sSTATE_KEY]) {
				_oSOVisibleState.data[_sSTATE_KEY]=_sOFF;
				setHelpersNotVisible();
			} else {
				if (_oSOVisibleState.data[_sSTATE_KEY]==_sON) {
					setHelpersVisible();
				} else {
					setHelpersNotVisible();
				}
			}
			doHelperHolder.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false, 0, true);
			setup();
		}
		
		private function onKeyDown(event : KeyboardEvent) : void {
			
			if (!FFFBase.get_oInstance().bHelpersEnabled) {
				return;
			}
			
			if ((event.charCode==uintTOGGLE_HELPER_CHAR_CODE_WIN || event.charCode == uintTOGGLE_HELPER_CHAR_CODE_MAC) && event.ctrlKey) {
				toggleHelpers();
			}
		}
		
		private function toggleHelpers() : void {
			if (_oSOVisibleState.data[_sSTATE_KEY] == _sOFF) {
				setHelpersVisible();
			} else {
				setHelpersNotVisible();
			}
		}

		private function setHelpersNotVisible() : void {
			_oSOVisibleState.data[_sSTATE_KEY] = _sOFF;
			for each (var doHelper : Helper in _a_doHelpers) {
				doHelper.visible=false;
			}
		}

		private function setHelpersVisible() : void {
			_oSOVisibleState.data[_sSTATE_KEY] = _sON;
			for each (var doHelper : Helper in _a_doHelpers) {
				doHelper.visible=true;
			}
		}

		private function onAddedToStage(event : Event) : void {
		}

		private function setup() : void {
			_a_doHelpers = new Array();
		}

		public function addHelper(doHelper : Helper) : void {
			registerHelper(doHelper);
		}
		
		private function registerHelper(doHelper : Helper) : void {
			
			if (_oSOVisibleState.data[_sSTATE_KEY] == _sOFF) {
				doHelper.visible=false;
			}
			
			_doHelperHolder.addChild(doHelper);
			_a_doHelpers.push(doHelper);
		}
	}
}
